/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.common.dataset.support.reader;

import org.vacoor.nothing.common.dataset.DatasetException;
import org.vacoor.nothing.common.dataset.DatasetReader;
import org.vacoor.nothing.common.dataset.RecordConsumer;

import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author vacoor
 */
public class CompoundReader implements DatasetReader {
    private List<DatasetReader> readers = new ArrayList<DatasetReader>();

    @Override
    public boolean support(BufferedInputStream bis) {
        try {
            bis.mark(0);
            for (DatasetReader dReader : readers) {
                boolean supported = dReader.support(bis);
                bis.reset();

                if (supported) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            throw new DatasetException(e);
        }
    }

    @Override
    public void read(BufferedInputStream bis, RecordConsumer reader) throws DatasetException {
        try {
            bis.mark(0);
            for (DatasetReader dReader : readers) {
                boolean supported = dReader.support(bis);
                bis.reset();

                if (supported) {
                    dReader.read(bis, reader);
                    break;
                }
            }
        } catch (Exception e) {
            throw e instanceof DatasetException ? (DatasetException) e : new DatasetException(e);
        }
    }

    public void addReader(DatasetReader reader) {
        this.readers.add(reader);
    }

    public List<DatasetReader> getReaders() {
        return readers;
    }

    public void setReaders(List<DatasetReader> readers) {
        this.readers = readers;
    }
}
